//Couldn't overload name Cipher.
//This class has two methods: packUp(Serializable, PublicKey)
//			      unpack(SealedObject, PrivateKey)
//			      They can push objects into an encrypted form
//			      and retrieve them.
//			      Retrieving them can happen at a different location



import javax.crypto.*;
import java.security.*;
import java.io.Serializable;
public class Xipher{
	public Cipher c;
    public Cipher d;
    public static final String algo = "RSA";

	public Xipher(){
		try{
        		c = Cipher.getInstance(algo);
                d = Cipher.getInstance(algo);
        	}
       		catch(Exception constructexcept){
            		System.out.println("Couldn't construct cipher.\n\n " + constructexcept);
        	}
	}

	public SealedObject packUp(Serializable obj, PublicKey theirpubkey){
	 if (obj == null){
		System.out.println("Obj is null");
	}
	else if(theirpubkey == null){
		System.out.println("Their pub key is null");
	}
	else if(c == null){
		System.out.println("Cipher is null");
	}
	else{
            try{
                c.init(c.ENCRYPT_MODE, theirpubkey);
		}
		catch(InvalidKeyException f){
			System.out.println("f");
		}
		catch(NullPointerException g){
			System.out.println(g);
		}
	    try{
                SealedObject toret = new SealedObject(obj, c);
                return toret;
            }
            catch(Exception packExcept){
                System.out.println("Couldn't pack exception.\n\n " + packExcept);
            }
	}
            return null;
    }
    public Object unpack(SealedObject obj, PrivateKey yourprivatekey){
            try{
                c.init(c.DECRYPT_MODE, yourprivatekey);;
                Object toret = obj.getObject(c);
                return toret;
            }
            catch(Exception unpackexcept){
                System.out.println("Couldn't unpack object" + unpackexcept);
            }
        return null;
    }
    public Cipher getCipher(PublicKey theirpubkey){
        try{
            c.init(Cipher.ENCRYPT_MODE, theirpubkey);
		}
		catch(InvalidKeyException f){
			System.out.println("f");
		}
		catch(NullPointerException g){
			System.out.println(g);
		}
        return c;
    }
    public Cipher getDCipher(PrivateKey yourprivatekey){
        try{
            d.init(Cipher.DECRYPT_MODE, yourprivatekey);
		}
		catch(InvalidKeyException f){
			System.out.println("f");
		}
		catch(NullPointerException g){
			System.out.println(g);
		}
        return d;
    }
}

